import allure
from selenium.common import WebDriverException

from utils.driver import Driver
from utils.logger import get_logger
import pytest
from config.config import Config
from utils.time_recorder import time_record

class BaseTest:
    driver = None
    logger = None


    @pytest.fixture(autouse=True, scope="session")
    def global_driver(self):
        """整个测试会话共享一个 driver（单例模式）"""
        if not hasattr(self, '_driver'):
            try:
                self._driver = Driver().get_driver()
                self.logger = get_logger()
                self.logger.info("全局 driver 初始化成功")
            except WebDriverException as e:
                self.logger.error(f"driver 初始化失败: {e}")
                raise
        yield self._driver
        # 会话结束后退出 driver
        if hasattr(self, '_driver') and self._driver:
            self._driver.quit()
            self.logger.info("全局 driver 已退出")


    @pytest.fixture(autouse=True)
    def setup_teardown(self,global_driver):
        """每个测试用例的前置后置操作（共享全局 driver）"""
        self.driver = global_driver
        self.logger.info("测试用例开始，使用全局 driver")

        yield  # 测试用例执行
        self.logger.info("yield后清理")
        # 每个测试用例结束后截图并附加到Allure报告
        if hasattr(self, 'driver') and self.driver:
            screenshot = self.driver.get_screenshot_as_png()
            allure.attach(
                screenshot,
                name=f"screenshot_{self.__class__.__name__}",
                attachment_type=allure.attachment_type.PNG
            )
        self.logger.info("每个测试用例结束后截图并附加到Allure报告")
        self.logger.info("每个测试用例结束后重新启动app")
        # 终止 APP（但不会关闭会话）

        self.driver.terminate_app(Config.capabilities['appium:appPackage'])  # Android 用包名，iOS 用 Bundle ID
        # 重新启动 APP
        self.driver.activate_app(Config.capabilities['appium:appPackage'])






